package com.ozo.easy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ozo.easy.common.log.SysLogDTO;
import com.ozo.easy.common.log.event.SysLogEvent;
import com.ozo.easy.common.model.*;
import com.ozo.easy.common.util.SortUtil;
import com.ozo.easy.entity.SysLog;
import com.ozo.easy.mapper.SysLogMapper;
import com.ozo.easy.pojo.dto.SysLogQueryDTO;
import com.ozo.easy.pojo.vo.SysLogVO;
import com.ozo.easy.service.ISysLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 系统日志 服务实现类
 *
 * @author ozo
 * @version 1.0
 * @date 2025-02-06 15:13:51
 */
@RequiredArgsConstructor
@Service
public class SysLogServiceImpl extends ServiceImpl<SysLogMapper, SysLog> implements ISysLogService {

    @Async
    @EventListener({SysLogEvent.class})
    public void saveSysLog(SysLogEvent event) {
        SysLogDTO sysLogDTO = (SysLogDTO) event.getSource();
        SysLog sysLog = BeanUtil.copyProperties(sysLogDTO, SysLog.class);
        baseMapper.insert(sysLog);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void remove(BaseBatchDTO<Long> batchDTO) {
        baseMapper.deleteBatchIds(batchDTO.getIdList());
    }

    @Override
    public PageResult<SysLogVO> page(BasePage basePage, SysLogQueryDTO queryDTO) {
        Integer pageNum = basePage.getPageNum();
        Integer pageSize = basePage.getPageSize();

        QueryWrapper<SysLog> queryWrapper = new QueryWrapper<>();
        // 排序
        String order = queryDTO.getOrder();
        if (StrUtil.isBlank(order)) {
            queryWrapper.lambda().orderByDesc(SysLog::getId);
        } else {
            SortUtil.setSortCondition(queryWrapper, queryDTO.getProp(), order);
        }
        // 条件
        queryWrapper.lambda()
                .like(StrUtil.isNotBlank(queryDTO.getOperationName()), SysLog::getOperationName, queryDTO.getOperationName());
        Page<SysLog> page = baseMapper.selectPage(new Page<>(pageNum, pageSize), queryWrapper);

        PageResult<SysLogVO> pageResult = new PageResult<>();
        pageResult.setPageNum(pageNum);
        pageResult.setPageSize(pageSize);
        pageResult.setPage(page.getPages());
        pageResult.setTotal(page.getTotal());
        List<SysLog> recordList = page.getRecords();

        List<SysLogVO> recordVOList = BeanUtil.copyToList(recordList, SysLogVO.class);

        pageResult.setResults(recordVOList);
        return pageResult;
    }

}
